package com.hoopchina.weibo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hoopchina.news.R;
import com.hoopchina.meta.BindItem;
import com.hoopchina.service.NewsService;
import com.hoopchina.ui.main.BaseActivity;
import com.hoopchina.ui.main.TitleBar;
import com.hoopchina.ui.main.ViewManager;
import com.hoopchina.util.NetUtil;
import com.hoopchina.weibo.Renren;
import com.hoopchina.weibo.Weibo;
import com.hoopchina.weibo.WeiboException;
import com.hoopchina.weibo.WeiboType;
import com.hoopchina.weibo.http.AccessToken;
import com.hoopchina.weibo.http.RequestToken;
import com.hoopchina.weibo.http.User;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * 
 * @author neusoft
 * 
 */
public class WeiboAuthActivity extends BaseActivity {
	public static final String Id = "WeiboAuthActivity";
	private static final String TAG = "WeiboAuthActivity";
	private static Class<?> mOldView = null;
	private static String mOldViewId = "";
	private static final String AUTH_VERIFIER = "oauth_verifier=";
	private static final String AUTH_NETBEAN_KEY_WORD = "http://api.t.163.com/oauth/authenticate?username";
	private static final String AUTH_RENREN_KEY_WORD = "http://graph.renren.com/oauth/login_success.html";
	private static final String RENREN_AUTH_URL = "http://graph.renren.com/oauth/authorize?display=touch&scope=status_update photo_upload&response_type=token&client_id=8e209d1a415a4d9d8f825642eedfb9d1&redirect_uri=http://graph.renren.com/oauth/login_success.html";
	public static final int MSG_GET_REQUEST_TOKEN_SUCCEED = 1;
	public static final int MSG_GET_REQUEST_TOKEN_FAILED = 2;
	public static final int MSG_GET_ACCESS_TOKEN_FAILED = 3;
	public static final int MSG_VERIFY_CREDENTIALS_FAILED = 4;
	public static final int MSG_AUTH_SUCCEED = 5;
	public static final int MSG_AUTH_FAILED = 6;
	
	private WebView mWebView = null;
	private TitleBar mTitleBar = null;
	private RelativeLayout mLoadingLayout = null;
	private int mWeiboType = 0;
	private String mAuthUrl = "";
	private String mTitle = "";
	private String mImageUrl = "";
	private String mNewsUrl = "";
	private String mAbs = "";
	private String mAuthor = "";
	private boolean mAuthSucceed = false;
	private boolean mAuthStart = false;
	private Renren mRenren = null;
	private boolean mReturnKeyPressed = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mMyHandleBackButton = true;
		Log.i(TAG, "onCreate enter");
		init();
		Log.i(TAG, "onCreate exit");
	}

	/*
	 * 消息处理
	 */
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_GET_REQUEST_TOKEN_SUCCEED:
				Log.i(TAG, "handleMessage MSG_GET_REQUEST_TOKEN_SUCCEED");
				initWebView();
				break;
			case MSG_GET_REQUEST_TOKEN_FAILED:
				Log.i(TAG, "handleMessage MSG_GET_REQUEST_TOKEN_FAILED");
				Toast.makeText(
						mViewManager.getCurrentActivity(),
						getResources().getString(
								R.string.forward_open_binding_page_error),
						Toast.LENGTH_SHORT).show();
				if(!mReturnKeyPressed)
				{
					goBack();
				}
				break;
			case MSG_GET_ACCESS_TOKEN_FAILED:
			case MSG_VERIFY_CREDENTIALS_FAILED:
			case MSG_AUTH_FAILED:
				Toast.makeText(
						mViewManager.getCurrentActivity(),
						getResources().getString(
								R.string.forward_authorize_error),
						Toast.LENGTH_SHORT).show();
				if(!mReturnKeyPressed)
				{
					goBack();
				}
				break;
			case MSG_AUTH_SUCCEED:
				Log.i(TAG, "handleMessage MSG_AUTH_SUCCEED");
				mAuthSucceed = true;
				Toast.makeText(
						mViewManager.getCurrentActivity(),
						getResources().getString(
								R.string.forward_binding_succeed),
						Toast.LENGTH_SHORT).show();
				if(!mReturnKeyPressed)
				{
					goBack();
				}
				break;
			}
		}
	};

	/**
	 * 初始化
	 */
	public void init() {
		clearCookies(WeiboAuthActivity.this);
		initUI();
		if (!NetUtil.checkNet(this)) {
			Toast.makeText(mViewManager.getCurrentActivity(),
					getResources().getString(R.string.app_no_network),
					Toast.LENGTH_SHORT).show();
			goBack();
			return;
		}
		NewsService.getTheadPool(true).submit(new Runnable() {
			@Override
			public void run() {
				if (!getRequestToken()) {
					mHandler.sendEmptyMessage(MSG_GET_REQUEST_TOKEN_FAILED);
				} else {
					mHandler.sendEmptyMessage(MSG_GET_REQUEST_TOKEN_SUCCEED);
				}
			}
		});
	}

	/**
	 * 初始化UI
	 */
	private void initUI() {
		Bundle intent = getIntent().getExtras();
		if (intent != null) {
			mWeiboType = intent.getInt("WeiboType");
			boolean fromBindingPage = intent.getBoolean("FromBindingPage");
			mTitle = intent.getString("Title");
			if (fromBindingPage) {
				mViewManager.setTitleBarVisibility(false);
				setContentView(R.layout.weiboauthview2);
				mTitleBar = (TitleBar) findViewById(R.id.authTitleBar);
				mTitleBar.setVisibility(View.VISIBLE);
				mTitleBar.setTitle(getResources().getString(
						R.string.forward_mybinding));
				mTitleBar.displayWeatherBox(false);
				mTitleBar.setStatus("");
			} else {
				setContentView(R.layout.weiboauthview);
				mImageUrl = intent.getString("ImageUrl");
				mNewsUrl = intent.getString("NewsUrl");
				mAbs = intent.getString("Abstract");
				mAuthor = intent.getString("Author");
			}
			mLoadingLayout = (RelativeLayout) findViewById(R.id.loadingLayout);
		}
		mViewManager.setTabBarVisibility(false);
		String bindText = getResources().getString(R.string.forward_binding);
		switch (mWeiboType) {
		case WeiboType.SinaType:
			mViewManager.setTitle(bindText
					+ getResources().getString(R.string.weibo_sina));
			break;
		case WeiboType.TencentType:
			mViewManager.setTitle(bindText
					+ getResources().getString(R.string.weibo_tencent));
			break;
		case WeiboType.SohuType:
			mViewManager.setTitle(bindText
					+ getResources().getString(R.string.weibo_sohu));
			break;
		case WeiboType.NetEaseType:
			mViewManager.setTitle(bindText
					+ getResources().getString(R.string.weibo_netease));
			break;
		case WeiboType.RenrenType:
			mViewManager.setTitle(bindText
					+ getResources().getString(R.string.weibo_renren));
			break;
		}
	}

	/**
	 * 获取Request Token
	 */
	private boolean getRequestToken() {
		Log.i(TAG, "getRequestToken enter");
		Weibo weibo = Weibo.getNewInstance(mWeiboType);
		if (mWeiboType == WeiboType.RenrenType) {
			mAuthUrl = RENREN_AUTH_URL;
		} else {
			RequestToken requestToken;
			try {
				requestToken = weibo.getOAuthRequestToken(mWeiboType);
				if (requestToken == null) {
					return false;
				}

				if (mWeiboType == WeiboType.NetEaseType) {
					mAuthUrl = requestToken.getAuthenticationURL()+"&client_type=mobile";
				} else {
					mAuthUrl = requestToken.getAuthorizationURL();
				}
			} catch (WeiboException e) {
				Log.i(TAG, "getRequestToken error");
				e.printStackTrace();
				return false;
			}
		}
		Log.i(TAG, "getRequestToken exit");
		return true;
	}

	/**
	 * 初始化WebView
	 */
	private void initWebView() {
		mWebView = (WebView) findViewById(R.id.authWebView);
		mWebView.getSettings().setJavaScriptEnabled(true);
		if(mWeiboType==WeiboType.SinaType||mWeiboType==WeiboType.TencentType||mWeiboType==WeiboType.RenrenType)
		{
			mWebView.getSettings().setSupportZoom(false);
			mWebView.getSettings().setBuiltInZoomControls(false);
		}
		else if(mWeiboType==WeiboType.SohuType)
		{
			mWebView.setInitialScale(60);
			mWebView.getSettings().setSupportZoom(true);
			mWebView.getSettings().setBuiltInZoomControls(true);
		}
		else if(mWeiboType==WeiboType.NetEaseType)
		{
			mWebView.setInitialScale(160);
			mWebView.getSettings().setSupportZoom(true);
			mWebView.getSettings().setBuiltInZoomControls(true);
		}
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.getSettings().setPluginsEnabled(true);
		mWebView.setEnabled(true);
		mWebView.requestFocus();
		mWebView.loadUrl(mAuthUrl);
		mLoadingLayout.setVisibility(View.GONE);
		mWebView.setVisibility(View.VISIBLE);
		mWebView.clearCache(true);

		mWebView.setWebViewClient(new WebViewClient() {
			// 载入网页
			public boolean shouldOverrideUrlLoading(final WebView view,
					final String url) {
				loadurl(view, url);
				return true;
			}

			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				Log.i(TAG, "errorCode=" + errorCode + "&error=" + description
						+ "&failingUrl" + failingUrl);
			}

			public void loadurl(final WebView view, final String url) {
				Log.i(TAG, "loadurl() enter url=" + url);
				if (mAuthStart)
					return;
				if (url.contains(AUTH_VERIFIER)
						|| url.contains(AUTH_NETBEAN_KEY_WORD)) {
					mAuthStart = true;
					startAuth(url);
				} else if (url.startsWith(AUTH_RENREN_KEY_WORD)) {
					mAuthStart = true;
					startRenrenAuth(url);
				} else {
					if (null == view || null == url) {
						return;
					}
					try {
						view.loadUrl(url);
					} catch (Exception e) {
					}
				}
			}

			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				Log.i(TAG, "onReceivedSslError() enter");
				handler.proceed();
			}

			public void onPageStarted(WebView view, String url, Bitmap favicon)
			{
				super.onPageStarted(view, url, favicon);
				if (mAuthStart)
					return;
				Log.i(TAG, "onPageStarted enter url = " + url);
				if (url.contains(AUTH_VERIFIER)) {
					mWebView.stopLoading();
					mAuthStart = true;
					startAuth(url);
				}
				if (url.contains(AUTH_NETBEAN_KEY_WORD)) {
					mWebView.setVisibility(View.INVISIBLE);
				}
				if (url.startsWith(AUTH_RENREN_KEY_WORD)) {
					mAuthStart = true;
					mWebView.stopLoading();
					startRenrenAuth(url);
				}
			}
			
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				Log.i(TAG, "onPageFinished enter url = " + url);
				if (mAuthStart)
					return;
				if (url.contains(AUTH_NETBEAN_KEY_WORD)) {
					mWebView.stopLoading();
					mAuthStart = true;
					startAuth(url);
				}
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	/**
	 * 系统按钮返回键按下响应
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			mReturnKeyPressed = true;
			goBack();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return false;
	}
	
	/**
	 * 页面返回
	 */
	public void goBack() {
		clearCookies(WeiboAuthActivity.this);
		Log.i(TAG, "goBack() enter");
		if (mAuthSucceed) {
			if (mOldViewId == BindingPageActivity.Id) {
				// 返回绑定页
				finish();
			} else {
				// 返回转发页
				ForwardingView.setOldView(mOldViewId, mOldView);
				Bundle aBundle = new Bundle();
				aBundle.putInt("WeiboType", mWeiboType);
				aBundle.putString("Title", mTitle);
				aBundle.putString("ImageUrl", mImageUrl);
				aBundle.putString("NewsUrl", mNewsUrl);
				aBundle.putString("Abstract", mAbs);
				aBundle.putString("Author", mAuthor);
				ViewManager.getInstance().showClearOnTopView(ForwardingView.Id,
						ForwardingView.class, false, aBundle);
			}
		} else {
			if (mOldView == BindingPageActivity.class) {
				finish();
			} else {
				ViewManager.getInstance().showView(mOldViewId, mOldView, false,
						null);
			}
		}
	}
	
	/**
	 * 开始认证
	 */
	public void startAuth(final String url) {
	//新浪、腾讯、网易、搜狐
		NewsService.getTheadPool(true).submit(new Runnable() {
			@Override
			public void run() {
				Log.i(TAG, "startAuth() run");
				String pin = "";
				int pos = url.indexOf(AUTH_VERIFIER);
				Weibo weibo = Weibo.getInstance(mWeiboType);
				AccessToken accessToken = null;
				if (pos != -1) {
					pin = url.substring(pos, url.length());
					pos = pin.indexOf("&");
					if (pos != -1) {
						pin = pin.substring(0, pos);
					}
					pin = pin.substring(pin.indexOf("=") + 1, pin.length());
				}
				accessToken = weibo.getAccessToken(pin);
				
				if (accessToken == null) {
					mHandler.sendEmptyMessage(MSG_GET_ACCESS_TOKEN_FAILED);
					return;
				}
				try {
					User user = weibo.verifyCredentials();
					if (user == null) {
						mHandler.sendEmptyMessage(MSG_VERIFY_CREDENTIALS_FAILED);
						return;
					}
					String id = "";
					String site = "";
					id = user.getScreenName();
					switch (mWeiboType) {
					case WeiboType.SinaType:
						site = getResources().getString(R.string.weibo_sina);
						break;
					case WeiboType.TencentType:
						site = getResources().getString(R.string.weibo_tencent);
						break;
					case WeiboType.SohuType:
						site = getResources().getString(R.string.weibo_sohu);
						break;
					case WeiboType.NetEaseType:
						site = getResources().getString(R.string.weibo_netease);
						break;
					}

					addBindingItem(id, site, mWeiboType,
							user.getProfileImageURL(), accessToken.getToken(),
							accessToken.getTokenSecret());
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(MSG_AUTH_SUCCEED);
			}
		});
	}

	/*
	 * 进行人人网认证
	 */
	public void startRenrenAuth(final String url) {
		NewsService.getTheadPool(true).submit(new Runnable() {
			@Override
			public void run() {
				Log.i(TAG, "startRenrenAuth in");
				mRenren = new Renren(url);
				try {
					if (!mRenren.getUserInfo()) {
						mHandler.sendEmptyMessage(MSG_AUTH_FAILED);
					}
				} catch (WeiboException e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(MSG_AUTH_FAILED);
				}

				addBindingItem(mRenren.getName(),
						getResources().getString(R.string.weibo_renren),
						mWeiboType, mRenren.getHeadUrl(),
						mRenren.getAccessToken(), "");
				mHandler.sendEmptyMessage(MSG_AUTH_SUCCEED);
			}
		});
	}

	/*
	 * 添加绑定项
	 */
	public void addBindingItem(String name, String site, int weiboType,
			String imageUrl, String accessToken,
			String accessTokenSecret) {
		BindingDBEngine mEngine = new BindingDBEngine(
				WeiboAuthActivity.this);
		BindItem bindItem = new BindItem();
		bindItem.setScreenName(name);
		bindItem.setSite(site);
		bindItem.setType(weiboType);
		bindItem.setHeadUrl(imageUrl);
		bindItem.setAccessToken(accessToken);
		bindItem.setTokenSecret(accessTokenSecret);
		mEngine.addBindingItem(bindItem);
	}
	
	/*
	 * 设置返回View
	 */
	public static void setOldView(String oldViewId, Class<?> oldViewClass) {
		mOldViewId = oldViewId;
		mOldView = oldViewClass;
	}
	
	/*
	 * 清除Http Cookies
	 */
    public static void clearCookies(Context context) {
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }
}
